import BinaryTreeNode from "../BinaryTreeNode";
import { isLine, Line3d } from "../../../math/Line3d";
import { isNull } from "../../../utils";
import { LineCmp } from "../../../utils/lineUtil";
export default class BinaryLineTreeNode extends BinaryTreeNode {
  constructor(value = null) {
    super(value);
  }

  insert(insertLine) {
    if (!isLine(insertLine)) return -1;
    if (isNull(this.value)) {
      this.value = insertLine;
      return this;
    }
    if (LineCmp.isIntersect(insertLine, this.value)) {
      const interPt = LineCmp.getInterPt(insertLine, this.value);
      this._insert(insertLine.startPt, interPt);
      this._insert(insertLine.endPt, interPt);
    } else if (this.value.isLeft(insertLine.startPt)) { // 未相交，判断是否在当前线段的左侧
      // Insert to the left.
      if (this.left) {
        return this.left.insert(insertLine);
      }
      const newNode = new BinaryLineTreeNode(insertLine);
      this.setLeft(newNode);
      return newNode;
    } else if (this.value.isRight(insertLine.startPt)) {// 未相交，判断是否在当前线段的左侧
      // Insert to the right.
      if (this.right) {
        return this.right.insert(insertLine);
      }
      const newNode = new BinaryLineTreeNode(insertLine);
      this.setRight(newNode);
      return newNode;
    }
    return this;
  }

  _insert(insertPt, interPt) {
    const newLine = new Line3d();
    newLine.setStartPt(insertPt);
    newLine.setEndPt(interPt);
    if (this.value.isLeft(insertPt)) {
      if (this.left) {
        return this.left.insert(newLine);
      }
      const newNode = new BinaryLineTreeNode(newLine);
      this.setLeft(newNode);
    } else if (this.value.isRight(insertPt)) {
      if (this.right) {
        return this.right.insert(newLine);
      }
      const newNode = new BinaryLineTreeNode(newLine);
      this.setRight(newNode);
    }
  }

  findPath(searchPt) {
    if (isNull(this.value)) return;
    const path = [];
    let curNode = this;
    let curVal = null;
    while (curNode) {
      curVal = curNode.value;
      path.push(curVal);
      if (curVal.isLeft(searchPt)) {
        curNode = curNode.left;
      } else if (curVal.isRight(searchPt)) {
        curNode = curNode.right;
      }
    }
    return path;
  }
}
